package cn.globalph.housekeeper.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.globalph.housekeeper.BuildConfig
import cn.globalph.housekeeper.Event
import cn.globalph.housekeeper.HouseKeeperApplication
import cn.globalph.housekeeper.data.TokenStorage
import cn.globalph.housekeeper.ui.BaseViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception

class LoginViewModel(
    private val repository: LoginRepository
) : BaseViewModel(){
    var userName = MutableLiveData<String>()
    var passWord = MutableLiveData<String>()


    private var _loginStatus = MutableLiveData<Boolean>()
    val loginStatus:LiveData<Boolean> = _loginStatus




    fun doLogin(){
        if(userName.value.isNullOrBlank()){
            _toastEvent.value = Event("用户名不能为空")
            return
        }
        if(passWord.value.isNullOrBlank()){
            _toastEvent.value = Event("密码不能为空")
            return
        }

        viewModelScope.launch {
            try {
                setLoading()
                var model = repository.doLogin(userName.value!!,passWord.value!!)
                setUnLoading()
                if(model.isSuccessful()){
                    TokenStorage.token = model.data!!.token
                    TokenStorage.setUserData(HouseKeeperApplication.instance.applicationContext,model.data!!)
                    _loginStatus.value = true
                }else {
                    _loginStatus.value = false
                    _toastEvent.value = Event(model.message)
                }
            }catch (e:Exception){
                if(BuildConfig.DEBUG) e.printStackTrace()
                _toastEvent.value = Event("网络异常，请重试")
                setUnLoading()
            }
        }
    }


}